/**
 * 版本信息Model页面
 */
import React, { Component } from 'react';
import { Button, Table, Row, Col, message, Modal } from 'antd';
import BreadcrumbCustom from '../../BreadcrumbCustom';
import ConditionFrom from './ConditionFrom';
import * as Request from '../../../Server/Upgrade';
import * as Constant from '../../../common/const';
import TablePage from '../../TablePage';
import qs from 'qs';
import {AuthButton,AuthA} from '../../auth/OperationAuth';

const confirm = Modal.confirm;
let id = '';
let lastIdValue = '';
let lastPage = {};
const formData = {
    "popupInfoCondition":{
        title:"泡泡条件信息",
        lastUrl: '/app/upgrade/version/popupInfo/'
    },
    "patchInfoCondition":{
        title:"升级包条件信息",
        lastUrl: '/app/upgrade/version/patchInfo/'
    }
};
const defaultPage = { page: Constant.DEFAULT_PAGE, size: Constant.DEFAULT_PAGE_SIZE };

class ConditionTable extends Component{
    constructor(props) {
        super(props);
        const { params } = this.props.match;
        lastPage = this.props.location.query;
        const paramId = params.id.split(',');
        id = paramId[0];
        lastIdValue = paramId[1];
        this.state = {
            loading: false, //表格加载样式
            data: [], //表格数据
            pagination: {},
            type: '', 
            title:'', //标题名称
            row: {}, //修改的单条记录
            flag: false //修改页面显示状态
        };
    }

    componentWillMount(){
        this.getTableData({...defaultPage, pId: id});
    }

    //查询表格数据方法
    getTableData = (param) =>{
        const { pagination } = this.state;
        //获取路径最后一个，判断
        const path = this.props.match.path
        const pathArr = path.split("/")
        const type = pathArr[pathArr.length -2];
        this.setState({ 
            type,
            title:formData[type].title,
            loading: true 
        });
        const _param = qs.stringify(param);
        if(type=='popupInfoCondition'){ //泡泡条件信息
            Request.getConditionPopup(_param).then(res => {
                if(res && res.code == Constant.REQUEST_SUCCESS){
                    const data = res.data;
                    this.setState({
                        data: data.content,
                        loading: false,
                        pagination: Object.assign(pagination, { total: data.totalSize, current: data.page + 1, pageSize: data.size }),
                    });
                }else{
                    this.setState({ loading: false});
                    res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg);
                }
            });
        }else{ //升级包条件信息
            Request.getConditionPatch(_param).then(res => {
                if(res && res.code == Constant.REQUEST_SUCCESS){
                    const data = res.data;
                    this.setState({
                        data: data.content,
                        loading: false,
                        pagination: Object.assign(pagination, { total: data.totalSize, current: data.page + 1, pageSize: data.size }),
                    });
                }else{
                    this.setState({ loading: false});
                    res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg);
                }
            });
        }
    }

    //上级菜单方法
    lastMenu = () =>{
        const { type } = this.state;
        this.props.history.push({
            pathname: formData[type].lastUrl+lastIdValue,
            query: lastPage
        });
    }

    /* 翻页 */
    handleTableChange = (pagination) => {
        const { type } = this.state
        const pager = { ...this.state.pagination };
        pager.current = pagination.current;
        pager.pageSize = pagination.pageSize;
        this.setState({
            pagination: pager
        });
        this.getTableData({
            page: pagination.current - 1,//后台分页默认从第0页开始
            size: pagination.pageSize,
            pId: id
        });
    }

    //删除方法
    deleteFunc = (row) =>{
        const param = {
            id: row.id
        };
        const _param = qs.stringify(param);
        confirm({
            title: '确定要删除该条信息？',
            maskClosable: true,
            okText: "确定",
            cancelText: "取消",
            onOk: () => this.onOkFunc(_param),
            onCancel() { },
        });
    }

    //删除确认方法
    onOkFunc = (_param) => {
        const { type } = this.state;

        if(type=='popupInfoCondition'){ //泡泡条件信息
            Request.conditionPopupDelete(_param).then(res => {
                if (res && res.code == Constant.REQUEST_SUCCESS) {
                    this.getTableData(this.getPageParams(true));
                    message.success('删除成功！', 1);
                } else {
                    res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg, 2)
                }
            });
        }else{
            Request.conditionPatchDelete(_param).then(res => {
                if (res && res.code == Constant.REQUEST_SUCCESS) {
                    this.getTableData(this.getPageParams(true));
                    message.success('删除成功！', 1);
                } else {
                    res.code !== Constant.REQUEST_UNAUTHORIZED && message.error(res.msg, 2)
                }
            });
        }
    }

    getPageParams = (isDelete) => {
        const { pagination } = this.state;
        const params = {
            page: pagination.current -1 ,//后台分页默认从第0页开始
            size: pagination.pageSize || Constant.DEFAULT_PAGE_SIZE,
            pId: id
        };
        if(isDelete && pagination.current == Math.ceil(pagination.total/pagination.pageSize)
            && pagination.total%pagination.pageSize == 1){
            params.page > 0 && params.page --;
        }
        return params;
    }

    //新增/修改方法
    showModelFunc = (row, flag) =>{
        this.setState({
            row,
            flag
        })
    }

    currentPageSize = () => this.state.pagination.pageSize || Constant.DEFAULT_PAGE_SIZE;

    render(){
        const { data, pagination, loading, type, title, flag, row } = this.state;
        const popupState = type=='popupInfoCondition';

        const columns = [
            {
                title: "主键",
                dataIndex: "id",
                align: 'center',
                width: '10%'
            }, {
                title: "函数",
                dataIndex: "fun",
                align: 'center',
                width: '22%',
            }, {
                title: "检查路径",
                dataIndex: popupState?"checkPath":"checkpath",
                align: 'center',
                width: '20%',
            }, {
                title: "参数",
                dataIndex: "param",
                align: 'center',
                width: '20%',
            }, {
                title: "外键",
                dataIndex: popupState?"popupId":"patchId",
                align: 'center',
                width: '15%',
            }, {
                title: "操作",
                align: 'center',
                width: '13%',
                render: (text, record) => (
                    <span>
                        <AuthA className='operation-primary' permission={'version:save'} onClick={()=>this.showModelFunc(record, true)}>编辑</AuthA>
                        <AuthA className='operation-danger' permission={'version:delete'} onClick={() => this.deleteFunc(record, type)}>删除</AuthA>
                    </span>
                )
            }
        ];


        
        return(
            <div>
                <BreadcrumbCustom first={title} />
                {flag&&<ConditionFrom
                    id={id}
                    row={row}
                    type={type}
                    showModelFunc={this.showModelFunc}
                    getTableData={this.getTableData}
                    current={pagination.current}
                    size={this.currentPageSize}
                />}
                <Row>
                    <Col span={2}>
                        <AuthButton size='large' permission={'version:get'} size='large' onClick={()=>this.lastMenu()}>上一级目录</AuthButton>
                    </Col>
                    <Col span={2} offset={1}>
                        <AuthButton size='large' permission={'version:save'} onClick={()=>this.showModelFunc({}, true)}>添加信息</AuthButton>
                    </Col>
                </Row>
                <TablePage
                    dataSource={data}
                    loading={loading}
                    columns={columns}
                    pagination={pagination}
                    onChange={this.handleTableChange}
                />
            </div>
        )
    }
}

export default ConditionTable